import { set, get, cloneDeep, isObject } from "lodash";
/* 转化入参数据结构 */
export function transformData2GUI(data = {}) {
  data = cloneDeep(data);
  const result = [];
  const iterator = (children, container, prevPath = []) => {
    Object.keys(children).forEach(key => {
      const path = prevPath.slice();
      path.push(key);
      const current = children[key];
      current.path = path;
      current.key = key;
      if (current.children && isObject(current.children)) {
        const childrenData = current.children;
        current.children = [];
        iterator(childrenData, current.children, path);
      }
      container.push(current);
    })
  }
  iterator(data, result);
  return result;
}

/* 处理默认值和当前值的合并 */
export function extractDefault({ config = {}, value = {} }) {
  const result = {};
  const iterator = (data, prePath = []) => {
    Object.keys(data).forEach(key => {
      const current = data[key];
      const path = prePath.slice();
      path.push(key);
      if (current.children) iterator(current.children, path);
      else {
        const pathStr = path.join(".");
        const val = get(value, pathStr) ?? current.default;
        set(result, pathStr, isObject(val) ? cloneDeep(val) : val);
      }
    })
  }
  iterator(config);
  return result;
}